var express = require('express');
var session = require('express-session');
var router = express.Router();

router.use(session({
  secret: 'secret', // 对session id 相关的cookie 进行签名
  resave: true, 
  saveUninitialized: true, // 是否保存未初始化的会话
  cookie: {
      maxAge: 1000 * 60 * 3 , // 设置 session 的有效时间，单位毫秒
      //1000 * 60 * 3
  },
}));

router.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Credentials', true);
  next();
});


/* GET home page. */
router.get('/login', function (req, res) {
  res.render('login.html');
});

// 用户登录
router.post('/login', function (req, res) {

  if (req.body.username == 'user01' && req.body.password == '123456') {
    req.session.userName = req.body.username; // 登录成功，设置 session
    res.json({ ret_code: 200, ret_msg: '登陆成功！', ret_url: '/' });
    req.session.uesr = req.body.username;
    res.redirect('main');
  } else {
    res.json({ ret_code: 1, ret_msg: '账号或密码错误' });// 若登录失败，重定向到登录页面

  }
});


// 获取主页

router.get('/', function (req, res) {

  if (req.session.userName) {
    console.log(req.session.userName);
    //判断session 状态，如果有效，则返回主页，否则转到登录页面
    res.render('main.html');
  } else {
        res.redirect('login');
  }
  res.end();
});


// 退出
router.get('/logout', function (req, res) {
  req.session.userName = null; // 删除session
  res.json({ ret_code: 200, ret_msg: '退出成功！', ret_url: '/' });
  res.end();
});

module.exports = router;
